package com.atzly.community.service.impl;

import com.atzly.community.constant.CommentConstant;
import com.atzly.community.entity.Comment;
import com.atzly.community.mapper.CommentMapper;
import com.atzly.community.mapper.DiscussPostMapper;
import com.atzly.community.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zlysimida
 * @date 2021/8/28 - 17:11
 */
@Service
//@Scope("prototype")
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Override
    public List<Comment> getCommentAndPage(int entityType, int entityId, int offset, int limit) {
        return commentMapper.getCommentAndPage(entityType,entityId,offset,limit);
    }

    @Override
    public int getComment(int entityType, int entityId) {
        return commentMapper.getComment(entityType,entityId);
    }

    // 设置隔离级别,传播性
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @Override
    public void saveComment(Comment comment, int discussId) {
        if(comment == null){
            throw new IllegalArgumentException("输入的参数不能为空!");
        }
        // 保存评论
        commentMapper.saveComment(comment);
        // 更新discuss表中的评论总数
        if(comment.getEntityType() == CommentConstant.ENTITY_TYPE_POST){
            int count = commentMapper.getComment(comment.getEntityType(), comment.getEntityId());
            discussPostMapper.updateDiscussPostCounts(comment.getEntityId(),count);
        }
    }

    @Override
    public Comment selectCommuntById(int entityId) {
        return commentMapper.selectCommentById(entityId);
    }


    @Override
    public Integer getCommentNumsByUserId(int userId, int entityTypePost, int entityTypeComment) {
        return commentMapper.getCommentNumsByUserId(userId,entityTypePost,entityTypeComment);
    }

    @Override
    public List<Comment> getCommentByUserPage(int userId, int entityTypePost, int entityTypeComment,int offset,int limit) {
        return commentMapper.getCommentByUserPage(userId, entityTypePost, entityTypeComment,offset,limit);
    }
}
